package com.rentalHome.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.rentalHome.domain.User;
import com.rentalHome.repository.UserRepository;
import com.rentalHome.util.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;



import java.io.IOException;
import java.util.List;


/**
 * @author LeeXyan
 */
@RestController
public class LoginController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
    private UserRepository userRepository;

	@PostMapping("/login")
	@ResponseBody
	public ResponseEntity sinIn(String account,String password, HttpServletRequest request) throws IOException {
		HttpResponse response = new HttpResponse();
        String  pd=getUserName(userRepository.findByUsername(account.trim()));

		if("admin".equals(account.trim()) && "123456".equals(password.trim())){
			response.setSuccessMsg("SUCCESS");
			HttpSession session = request.getSession();
			session.setAttribute("msg", "SUCCESS");
			session.setMaxInactiveInterval(20 * 60);
		}else if(password.trim().equals(pd)){

		}else{
			response.setSuccessMsg("ERROR");
		}

		return ResponseEntity.ok(response);
	}
	

	public String getUserName(List<User> users){
		return users.stream().findFirst().get().getPassword();
	}
}
